/*
 * SDLResource.cpp
 *
 *  Created on: Nov 21, 2010
 *      Author: timmeh
 */


#include <iostream>
#include "SDLResource.h"
#include "Vector2.h"
using namespace std;
using namespace bo_sdl;

bo_sdl::SDLResource::SDLResource(){}
bo_sdl::SDLResource::~SDLResource() {
	SDL_FreeSurface(fScreen);
	SDL_Quit();
}

SDLResource* SDLResource::fInstance = NULL;

/**
 * Returns the current instance of the screen. Self-initializes iff no screen found
 */
SDLResource* bo_sdl::SDLResource::Instance(){
	if (fInstance == NULL){
		fInstance = new SDLResource;
	}
	return fInstance;
}

/**
 * Initializes the SDL Layer using the supplied screen size
 */
bool bo_sdl::SDLResource::Initialize(int xScreen, int yScreen, double scale){
	if (SDL_Init(SDL_INIT_VIDEO) == 1)
		return false;
	if (TTF_Init() == -1)
		return false;
	fScreen = SDL_SetVideoMode(xScreen, yScreen, 24, SDL_DOUBLEBUF);
	if (!fScreen)
		return false;
	this->fScale = scale;
	return true;
}
/**
 * Blit the used sprite (fSprite) on the screen
 */
void bo_sdl::SDLResource::BlitToScreen(SDL_Surface* img, Vector2 pos){
	if ( !this->fBGBlitted ){
		this->BlitBackground();
		this->fBGBlitted = true;
	}
	SDL_Rect dest;
	dest.x = pos.GetX();
	dest.y = pos.GetY();
	dest.w = img->w;
	dest.h = img->h;
	// src = null -> blit entire sprite on screen
	SDL_BlitSurface(img, NULL, fScreen, &dest);
}

/**
 * Returns the scale, to be used in the visualize methods
 */

double bo_sdl::SDLResource::GetScale(){
	return this->fScale;
}

/**
 * Sets the background sprite to be used
 */

void bo_sdl::SDLResource::SetBackground(const char* fileName){
	this->fBackground = IMG_Load(fileName);
}

/**
 * Blits the background on the screen
 */

void bo_sdl::SDLResource::BlitBackground(){
	SDL_Rect dest;
	dest.x = 0;
	dest.y = 0;
	dest.w = this->fBackground->w;
	dest.h = this->fBackground->h;
	SDL_BlitSurface(this->fBackground, NULL, this->fScreen, &dest);
}
/**
 * Flips the screen
 */
void bo_sdl::SDLResource::FlipScreen(){
	SDL_Flip(fScreen);
}

/**
 * Clears the back buffer, fills it with black
 */
void bo_sdl::SDLResource::ClearBackBuffer(){
	SDL_FillRect(fScreen, 0, 0);
	this->fBGBlitted = false;
}

void bo_sdl::SDLResource::DrawHUDRect(){
    SDL_Surface* surface = SDL_CreateRGBSurface(SDL_SWSURFACE, 8 * this->fScale,0.25 * this->fScale,32,0,0,0,0);
    Vector2 tempPos(0, 5.75 * this->fScale);
	BlitToScreen(surface, tempPos);
}

void bo_sdl::SDLResource::DrawText(const char* string){
	SDL_Surface* text;
	if ( this->fFont == 0 )
		this->fFont = TTF_OpenFont( "font.ttf", 20 );
	SDL_Color textColor = { 255, 255, 255 };
	text = TTF_RenderText_Solid( this->fFont, string, textColor );
	Vector2 tempPos(0.1*this->fScale, 5.8*this->fScale);
	BlitToScreen(text, tempPos);
}

